<template>
  <div class="pt-20" style="min-height: 100px">
    <section class="flex-1 pb-50 bg-white">
      <div
        class="w-full pt-10 pb-6 bg-gradient-to-b from-[#f7f7f7] from-0% to-[#fff] to-100%"
      >
        <div
          class="w-full max-w-screen-xl flex items-center justify-between m-auto px-11 space-x-7"
        >
          <div class="max-w-[912px] flex flex-1 items-center space-x-10 justify-between">
            <div class="flex space-x-4 items-center">
              <nav class="dioa-breadcrumb__container">
                <ol class="dioa-breadcrumb__list flex items-center">
                  <li class="dioa-breadcrumb__item flex items-center flex-shrink-0">
                    <a
                      href="/"
                      class="dioa-breadcrumb__link transition text-neutral-60 text-base hover:underline flex-shrink-0"
                      >首页</a
                    >
                    <span
                      aria-hidden="true"
                      class="dioa-breadcrumb__separator mx-2 text-neutral-50 w-[14px] h-[14px] block rotate-[120deg]"
                      ><svg
                        viewBox="0 0 24 24"
                        width="24"
                        height="24"
                        class="dioa-icon w-full h-full"
                      >
                        <line
                          x1="2"
                          y1="12"
                          x2="23"
                          y2="12"
                          stroke="currentColor"
                          stroke-width="2"
                          stroke-linecap="round"
                          stroke-linejoin="round"
                        ></line></svg
                    ></span>
                  </li>

                  <li
                    class="dioa-breadcrumb__item flex items-center flex-shrink overflow-hidden"
                  >
                    <span
                      aria-current="page"
                      class="dioa-breadcrumb__current-page text-black text-2xl font-medium line-clamp-1"
                      >{{ detailname }}</span
                    >
                  </li>
                </ol>
              </nav>
            </div>
          </div>
        </div>
      </div>

      <div class="w-full max-w-screen-xl flex items-start m-auto px-11 space-x-7">
        <div class="flex-1 max-w-[912px] relative">
          <div class="dioa-box group">
            <videoPlay :videoUrl="detail.videoSkimUrl" v-if="detail !== null" />
          </div>
          <p class="mt-5 text-neutral-50 text-base">{{ detailconfig }}</p>
          <div class="w-full flex items-center justify-between mt-4">
            <div class="flex items-center space-x-8">
              <!--$--><a class="outline-none"
                ><button
                  class="flex items-center space-x-1 text-black hover:text-black-50 transition"
                  @click="loveFun()"
                >
                  <i class="iconfont" style="margin-right: 5px">
                    {{ !islove ? "&#xe632;" : "&#xe625;" }}
                  </i>
                  {{ !islove ? "收藏" : "已收藏" }}
                </button></a
              >
            </div>
            <div class="space-x-5">
              <button
                type="button"
                @click="downmini(detail?.videoSkimUrl)"
                class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-10 px-5 text-base font-medium text-black bg-neutral-30 hover:bg-neutral-40 active:bg-black active:text-white disabled:text-neutral-40 disabled:bg-neutral-30 data-loading:text-transparent data-loading:bg-neutral-30 rounded-full border-0"
              >
                下载小样
              </button>
            </div>
          </div>
          <div class="w-full mb-15 mt-12 p-13 bg-neutral-20 rounded-xl">
            <div class="w-full flex flex-wrap -mb-10 justify-between">
              <div class="text-left space-y-3 mb-10 mr-17 last:mr-0">
                <p class="text-2xl font-medium text-black">{{ detail?.createTime }}</p>
                <p class="text-base text-neutral-60">上传时间</p>
              </div>
              <div class="text-left space-y-3 mb-10 mr-17 last:mr-0">
                <p class="text-2xl font-medium text-black">
                  {{ detail?.categoryNames ? detail?.categoryNames : "未知" }}
                </p>
                <p class="text-base text-neutral-60">素材类型</p>
              </div>
              <!-- <div class="text-left space-y-3 mb-10 mr-17 last:mr-0">
                <p class="text-2xl font-medium text-black">1920*1080</p>
                <p class="text-base text-neutral-60">分辨率</p>
              </div> -->
              <div class="text-left space-y-3 mb-10 mr-17 last:mr-0">
                <p class="text-2xl font-medium text-black">{{ detail?.frameRate }}</p>
                <p class="text-base text-neutral-60">帧率</p>
              </div>
            </div>
          </div>
          <h3 class="text-3xl font-medium mb-7 mt-12">素材详情</h3>

          <div
            class="w-full max-h-[1824px] mt-5 overflow-hidden rounded-md"
            v-html="detail?.materialDetail"
          ></div>
        </div>

        <div class="w-[412px] flex-shrink-0">
          <div class="w-full bg-white shadow-lg rounded-xl py-7 px-7">
            <div class="h-[26px] flex items-center justify-between">
              <h3 class="text-lg font-medium text-black">
                选择授权类型
                <el-tag type="danger">{{
                  detail?.vrType == "0" ? "普通素材" : "360素材"
                }}</el-tag>
              </h3>
            </div>
            <div
              class="dioa-radio__group grid-flow-col flex flex-col space-y-1 mt-4 gap-0 p-2 bg-neutral-10 rounded-lg"
            >
              <el-radio-group v-model="radio" @update:modelValue="handleRadioChange">
                <template v-for="(item, index) in authList" :key="item.id">
                  <el-radio :value="index">
                    <template #default>
                      <!-- 这里可以自定义显示内容 -->
                      <div class="flex items-center justify-between" style="width: 300px">
                        {{ item.authType }}
                      </div>
                    </template>
                  </el-radio>
                </template>
              </el-radio-group>
            </div>
            <div class="h-[26px] flex items-center justify-between pt-5">
              <h3 class="text-lg font-medium text-black">选择视频规格</h3>
            </div>
            <div
              class="dioa-radio__group grid-flow-col flex flex-col space-y-1 mt-4 gap-0 p-2 bg-neutral-10 rounded-lg"
            >
              <el-radio-group v-model="radio1" @update:modelValue="handleRadioChange1">
                <template v-for="(item, index) in specList" :key="item.id">
                  <el-radio :value="index">
                    <template #default>
                      <!-- 这里可以自定义显示内容 -->
                      <div class="flex items-center justify-between" style="width: 300px">
                        <span>{{ item.specs }} </span>
                        <span>￥ {{ item.price }}</span>
                      </div>
                    </template>
                  </el-radio>
                </template>
              </el-radio-group>
            </div>
            <div class="mt-5 space-y-4">
              <button
                v-if="isdown"
                type="button"
                class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-14 px-10 text-lg font-medium lg:h-12 lg:px-8 text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 rounded-full border-0 w-full"
                @click="mustdownm"
              >
                立即下载
              </button>
              <button
                v-else
                type="button"
                class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-14 px-10 text-lg font-medium lg:h-12 lg:px-8 text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 rounded-full border-0 w-full"
                @click="msutbuy"
              >
                立即购买
              </button>
              <div>
                <button
                  type="button"
                  @click="addCart"
                  class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-14 px-10 text-lg font-medium border-2 lg:h-12 lg:px-8 text-black border-black bg-white hover:bg-neutral-30 active:bg-neutral-40 disabled:bg-white disabled:text-neutral-50 disabled:border-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 data-loading:border-neutral-40 rounded-full w-full"
                >
                  加入购物车
                </button>
              </div>
            </div>

            <div class="w-full bg-neutral-10 mt-4 rounded-md py-2 px-5">
              <div
                class="w-full flex items-center h-[46px] text-base space-x-2"
                v-for="(item, index) in authDescList"
                :key="index"
              >
                <svg
                  viewBox="0 0 24 24"
                  width="18"
                  height="18"
                  class="dioa-icon fill-red text-white"
                >
                  <circle cx="12" cy="12" r="9.6"></circle>
                  <svg
                    viewBox="0 0 24 24"
                    width="20"
                    height="20"
                    class="dioa-icon stroke-current"
                    x="2"
                    y="2"
                  >
                    <polyline
                      points="7,11.98 10.75,15.43 17,9"
                      fill="none"
                      stroke-linejoin="round"
                      stroke-linecap="round"
                      stroke-width="2.29"
                    ></polyline>
                  </svg>
                </svg>
                <p class="text-neutral-60">{{ item }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--/$-->
    </section>
  </div>
  <!-- 下载机器码填写 -->
  <MyDialog @update:visible="updateDialog" :initVisible="dialogVisible" :width="400">
    <div class="closeBtn">
      <el-button @click="handleClose" circle><i class="iconfont">&#xe60e;</i></el-button>
    </div>
    <!-- 这里可以放置对话框内容 -->
    <div class="editInput">
      <el-form :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.code" placeholder="请输入机器码" clearable />
        </el-form-item>

        <el-form-item>
          <button
            type="button"
            class="dioa-button__root inline-flex appearance-none items-center justify-center select-none relative whitespace-nowrap align-middle transition outline-none cursor-pointer disabled:cursor-not-allowed h-14 px-10 text-lg font-medium lg:h-12 lg:px-8 text-white bg-red hover:bg-neutral-60 active:bg-black disabled:bg-neutral-40 data-loading:text-transparent data-loading:bg-neutral-40 rounded-full border-0 w-full"
            @click="onSubmitdown"
          >
            提交
          </button>
        </el-form-item>
      </el-form>
    </div>
  </MyDialog>
</template>

<script setup lang="ts">
import videoPlay from "@/components/Video.vue";

import {
  getMaterialdetai,
  getauthTypeList,
  checkCollectId,
  collectAdd,
  collectDel,
  getPrice,
  checkPermissions,
  downloadDetail,
  getdetailConfig,
} from "@/common/listApi";
import { saveCart } from "@/common/userApi";
import { HdMaterialDetailVo } from "@/common/utils/homeTpye";
import { ref, computed, watch, reactive } from "vue";
import { useUserStore } from "@/store/loginStore";
import { getCurrentInstance } from "vue"; //各个组件自由获取
import { ElMessage } from "element-plus";
import { authDescType } from "@/common/utils/listType";
import MyDialog from "@/components/MyDialog.vue";
import { saveAsPbtxt } from "@/common/common";
import { useRoute, useRouter } from "vue-router";
import { userorderStore } from "@/store/orderStore";
const orderStore = userorderStore();
const router = useRoute();
const routerpush = useRouter();

const paramId = ref<any>(null);
paramId.value = router.params.id; //地址栏参数id获取

// 获取素材详情
const detail = ref<HdMaterialDetailVo | null | any>(null);
const detailname = ref("");
const detailPic = ref("");
getMaterialdetai(paramId.value).then((res) => {
  console.log(res.data);
  detail.value = res.data;
  detailname.value = res.data.name;
  detailPic.value = res.data.thumbnailUrl;
  isCheckCollect(paramId.value);
});
// 获取素材声明
const detailconfig = ref("");

getdetailConfig().then((result) => {
  detailconfig.value = result.data.configValue;
});
// 获取授权列表getauthTypeList authDescList
const authList = ref<any>(null);
const authDescList = ref<authDescType | any>([]);
const radio = ref(0); //授权radio
const authId = ref(0); //选中的授权id
const specId = ref(0); //选中规格id
const skuName = ref(""); //选中的名称
const priceSelcet = ref("0"); //选中的价格
const priceSelectid = ref(0); //选中的价格id
getauthTypeList(2).then((res) => {
  console.log(res.data, "sho0uquan");
  authList.value = res.data;
  authDescList.value = res.data[radio.value].authDescList;
  getmaterialdetail(authList.value[radio.value].id);
});

const handleRadioChange = (value: number) => {
  console.log("当前选中的值：", value);
  radio.value = value;
  radio1.value = 0;
  authDescList.value = authList.value[value].authDescList;
  getmaterialdetail(authList.value[radio.value].id);
};

// 获取素材规格materialdetail
const specList = ref<any>([]);
const radio1 = ref(0); //规格radio
const isdown = ref(false); //是否有下载权限
const getmaterialdetail = (id: string) => {
  getPrice(paramId.value, id).then((result) => {
    console.log(result, "specList");
    specList.value = result.data;
    // specId.value = specList.value[radio1.value].id; //获取的收取规格id
    authId.value = specList.value[0].authTypeId;
    specId.value = specList.value[0].marterialDetailId;
    skuName.value = specList.value[0].specs;
    priceSelcet.value = specList.value[0].price;
    priceSelectid.value = specList.value[0].id;
    checkitem(specList.value[0].id, specList.value[0].marterialDetailId);
  });
};
// 切换规格
const handleRadioChange1 = (value: number) => {
  console.log("当前选中的值：", specList.value[value].id);
  radio1.value = value;
  authId.value = specList.value[value].authTypeId;
  specId.value = specList.value[value].marterialDetailId;
  skuName.value = specList.value[value].specs;
  priceSelcet.value = specList.value[value].price;
  priceSelectid.value = specList.value[value].id;
  checkitem(specList.value[value].id, specList.value[value].marterialDetailId);
};
// 检查规格素材是否有下载权限checkPermissions
const checkitem = (id: number, marterialDetailId: number) => {
  checkPermissions(id, marterialDetailId).then((result) => {
    console.log(result);
    isdown.value = result.data;
  });
};
// 收藏checkCollectId
const islove = ref(false); //判断是否收藏过
const isCheckCollect = (id) => {
  checkCollectId(id).then((result) => {
    if (result.code == 200) {
      islove.value = result.data;
    }
  });
};

// 判断是否登录过
const userStore = useUserStore();
const isLoggedIn = computed(() => userStore.isLogin);

// 点击收藏按钮
const loveFun = () => {
  console.log(islove.value);
  if (!isLoggedIn.value) {
    handleClick();
  } else {
    // islove.value = !islove.value;
    addLove();
  }
};
// 添加收藏collectAdd,collectDel
const addLove = () => {
  if (!islove.value) {
    collectAdd(paramId.value).then((result) => {
      console.log(result);
      if (result.code == 200) {
        console.log("添加收藏");
        ElMessage("收藏成功");
        islove.value = true;
      } else {
        ElMessage(result.msg);
      }
    });
  } else {
    collectDel(paramId.value).then((result) => {
      console.log(result);
      if (result.code == 200) {
        console.log("添加收藏");
        ElMessage("已取消收藏");
        islove.value = false;
      } else {
        ElMessage(result.msg);
      }
    });
  }
};
// 下载小样
const downmini = (url: string) => {
  // window.open(url);
  saveAsPbtxt(url, url);
};

// 打开机器ma
const dialogVisible = ref(false);
const openDialog = () => {
  // console.log(dialogVisible, "!23");
  dialogVisible.value = true;
  formInline.code = "";
};
const updateDialog = (value: boolean) => {
  // console.log(dialogVisible, "!23");
  dialogVisible.value = value;
};
const handleClose = () => {
  dialogVisible.value = false;
  // isOpen.value = false;
};
const formInline = reactive({
  code: "",
});
// 下载素材downloadDetail
const onSubmitdown = () => {
  if (!isLoggedIn.value) {
    handleClick();
  } else {
    if (formInline.code == "") {
      ElMessage.error("请输入机器码");
      return;
    }
    downloadDetail(specId.value, priceSelectid.value, formInline.code).then((result) => {
      console.log(result);
      if (result.code == 200) {
        // download(result.data);
        saveAsPbtxt(result.data, result.data);

        handleClose();
      } else {
        ElMessage.error(result.msg);
      }
    });
  }
};

const mustdownm = () => {
  console.log(authId.value, specId.value);
  openDialog();

  // window.open(url);
};
// 立即购买
const msutbuy = () => {
  if (!isLoggedIn.value) {
    handleClick();
  } else {
    // islove.value = !islove.value;
    let param = reactive({
      orderType: "1",
      orderAmount: priceSelcet,
      payType: "1",
      itemBos: [
        {
          itemType: "1",
          itemId: specId,
          priceId: priceSelectid,
          itemName: skuName,
          itemAmount: priceSelcet,
          quantity: 1,
          baseAmount: priceSelcet,
          thumbnailUrl: detail.value.thumbnailUrl,
        },
      ],
    });
    orderStore.updataPostOrderData(param);
    console.log("立即购买", param);
    localStorage.setItem("orderData", JSON.stringify(param));
    routerpush.push({ name: "buy" });
  }
};
// 加入购物车
const dataparamcart = reactive({
  spuId: paramId,
  skuId: specId,
  skuName: skuName,
  spuName: detailname,
  quantity: 1,
  priceId: priceSelectid,
  addPrice: priceSelcet,
  picUrl: detailPic,
});
const addCart = () => {
  if (!isLoggedIn.value) {
    handleClick();
  } else {
    // islove.value = !islove.value;
    console.log(dataparamcart, "加入购物车");

    saveCart(dataparamcart).then((result) => {
      if (result.code == 200) {
        ElMessage({
          message: "添加成功",
          type: "success",
          plain: true,
        });
      }
    });
  }
};

// 监控登录情况
watch(
  () => userStore.isLogin,
  (newValue, oldValue) => {
    radio1.value = 0; //规格radio
    radio.value = 0;
    if (newValue) {
      // addLove();
      isCheckCollect(paramId.value);
      // checkitem(specList.value[0].id, specList.value[0].marterialDetailId);
    } else {
      islove.value = false;
      isdown.value = false;
    }
  }
);
// 控制头部组件打开登录按钮
const instance = getCurrentInstance();
const handleClick = () => {
  instance?.proxy?.$Bus.emit("h-click");
};
</script>

<style>
.el-radio-group {
  display: block;
}
.el-radio {
  /* display: inline-block; */
  white-space: normal;
  margin-right: 0;
  height: 50px;
  line-height: 50px;
  padding: 0 15px;
}
.el-radio__label {
  font-size: 15px;
}
/* 定义颜色变量 */
.el-radio__input.is-checked + .el-radio__label {
  color: #dd1a20 !important;
}
.el-radio__input.is-checked .el-radio__inner {
  background: #dd1a20 !important;
  border-color: #dd1a20 !important;
}

/* 覆盖Element UI默认的按钮颜色 */
.el-message-box .el-button {
  background-color: #dd1a20; /* 你想要的任何颜色 */
  border-color: #dd1a20;
}
.closeBtn {
  padding: 30px 30px 0 0;
  text-align: right;
}
.editInput {
  padding: 20px;
}
</style>
